<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) 2015-2016 http://www.clcw.com.cn All rights reserved.    |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                               |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: Xmh <xiangminghu@clcw.com.cn>                                  |
// +------------------------------------------------------------------------+
//

namespace AuctionAppApi\Controller;

use AuctionCore\Common\AntNest;
use AuctionCore\Common\PhpRedis;
use Think\Controller;
use AuctionCore\System\AuctionException;
use AuctionCore\CarDealer\Dealer;
use AuctionCore\Other\Address;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\CarResource\Car;
use AuctionCore\System\SystemConf;
use AuctionCore\Other\Coupon;
use AuctionCore\CarDealer\TakeMan;
use AuctionCore\Common\Image;

//weaver 客户端 START-----------------------
require_once MODULE_PATH . 'Org/Thrift/Lib/Thrift/ClassLoader/ThriftClassLoader.php';

use Services\AuctionService\AuctionServiceClient;
use Thrift\ClassLoader\ThriftClassLoader;

$loader = new ThriftClassLoader();
$loader->registerNamespace('Thrift', MODULE_PATH . 'Org/Thrift/Lib');
$loader->registerDefinition('Services', MODULE_PATH . 'Org/Thrift/gen-php');
$loader->register();

use Thrift\Protocol\TBinaryProtocol;
use Thrift\Protocol\TMultiplexedProtocol;
use Thrift\Transport\THttpClient;
use Thrift\Transport\TBufferedTransport;
use Thrift\Exception\TException;
//weaver 客户端 END-----------------------


/**
 * 车商相关信息
 *
 * @author Xmh
 */
class DealerController extends BaseController {

    public function __construct() {
        $this->h5_actions = array(
            //'C_DEALER|A_INVITE'
        );
        $this->html5_actions = array(
            'C_DEALER|A_INVITE',
            'C_DEALER|A_CUTDOWN'
        );
        parent::__construct();
        $this->dealer_id = I('param.dealer_id/d');

        $exclude_c = array(
            'C_DEALER|A_INVITE',
            'C_DEALER|A_CUTDOWN',
            'C_DEALER|A_SEND_VERIFY_CODE',
            'C_DEALER|A_DO_CUTDOWN',
        );

        $ca = strtoupper('C_'.CONTROLLER_NAME."|A_".ACTION_NAME);
        if(!in_array( $ca,$exclude_c)){
            if (empty($this->dealer_id)) {
                AuctionException::make_throw('500001');
            }
        }

        $this->dealer = new Dealer($this->dealer_id);
        $this->coupon = new Coupon($this->dealer_id);
        $this->take_man = new TakeMan($this->dealer_id);
        $this->address = new Address();
//        $this->dealerfeedback = new \AuctionCore\Other\DealerFeedback();

    }

    /**
     * 我的信息页面：头像、名称、类型、可用保证金、冻结保证金、代金券
     * return json 我的页面信息
     */
    public function index() {
        $coupon = $this->coupon->coupon_stat();
        $dealer[] = $this->dealer->dealer_base_info($this->dealer_id,$this->uid);
        if (array_filter($dealer)) {
            $dealer_info = array();
            foreach ($dealer as $d) {
                $dealer_info['avatar'] = $d['avatar'];
                $dealer_info['real_name'] = $d['real_name'];
                $dealer_info['remain_amount'] = (int)$d['bail_amount'];
                $dealer_info['free_amount'] = (int)$d['freeze_amount'];
                $dealer_info['coupon_money'] = $coupon['cur_amount_sum'] ? (int)$coupon['cur_amount_sum'] : "0";
                $dealer_info['level'] = C('DEALER_LEVEL')[$d['level']];
            }
            $this->api_200($dealer_info);
        } else {
            AuctionException::make_throw("500012");
        }
    }

    /**获取个人信息
     * @throws AuctionException
     */
    public function index_v160() {
        $coupon = $this->coupon->coupon_stat();
        $dealer = $this->dealer->dealer_base_info($this->dealer_id,$this->uid);
        if ($dealer) {
            $dealer_info['avatar'] = $dealer['avatar']?$dealer['avatar']:get_style_cdnurl().'app/images/bg_head.png';
            $dealer_info['real_name'] = $dealer['real_name'];
            $dealer_info['remain_amount'] = (int)$dealer['bail_amount'];
            $dealer_info['free_amount'] = (int)$dealer['freeze_amount'];
            $dealer_info['minus_amount'] = (int)$dealer['minus_amount'];  //维保透资金额
            $dealer_info['coupon_money'] = $coupon['cur_amount_sum'] ? (int)$coupon['cur_amount_sum'] : "0";
            $dealer_info['level_name'] = C('DEALER_LEVEL')[$dealer['level']];
            $dealer_info['level'] = $dealer['level'];
            //认证类型
            //$dealer_info['auth_type'] = C('DEALER_TYPE')[$dealer['auth_type']];
            //认证审核状态
            $dealer_info['auth_status'] = $dealer['auth_status'];
            $dealer_info['auth_status_name'] = C('DEALER_AUTH_STATUS')[$dealer['auth_status']];

            if($dealer_info['auth_status']==2){
                $dealer_info['auth_status_name'] = $dealer['auth_type']==1?'个人签约':'企业签约';
                $dealer_info['auth_status'] = 3;
            }elseif($dealer_info['auth_status']==3){
                $dealer_info['auth_status'] = 2;
            }
            if($dealer['is_agree_agreement']){
                $dealer_info['auth_status'] = 4;
                unset($dealer_info['auth_status_name']);
            }
            $this->api_200($dealer_info);
        } else {
            AuctionException::make_throw("500012");
        }
    }

    /**
     * 账户中心 - 基本信息
     * 车商 - 车商基本信息
     * return json 车商基本信息
     */
    public function dealer_base() {
//        $dealer_base[] = $this->dealer->getDealerById($this->dealer_id);
        $dealer_base[] = $this->dealer->dealer_base_info($this->dealer_id,$this->uid);
        if (array_filter($dealer_base)) {
            $dealer_base_info = array();
            foreach ($dealer_base as $db) {
                $dealer_base_info['avatar'] = $db['avatar'];
                $dealer_base_info['org_code'] = $db['org_code'];
                $dealer_base_info['fullname'] = $db['fullname'];
                $dealer_base_info['shortname'] = $db['shortname'];
                $dealer_base_info['type'] = C('COMPANY_TYPE')[$db['type']];
                $dealer_base_info['level'] = C('DEALER_LEVEL')[$db['level']];
                $dealer_base_info['contact_person'] = $db['contact_person'];
                //$dealer_base_info['contact_mobile'] = $db['contact_mobile'];
                $dealer_base_info['contact_mobile'] = $db['pwd_mobile'];
//                $dealer_base_info['province'] = $this->address->get_name_by_code($db['province']);
//                $dealer_base_info['city'] = $this->address->get_name_by_code($db['city']);
                $dealer_base_info['area'] = $this->address->get_name_by_code($db['province']) . ' - ' . $this->address->get_name_by_code($db['city']); //$this->address->get_name_by_code($db['area'])
                $dealer_base_info['address'] = $db['address'];
                $dealer_base_info['postcode'] = $db['postcode'];
            }
            $this->api_200($dealer_base_info);
        } else {
            AuctionException::make_throw("500012");
        }
    }



    /**
     * 账户中心 - 基本信息
     * 车商 - 车商基本信息
     * return json 车商基本信息
     */
    public function dealer_info() {
        $dealer_base = $this->dealer->dealer_base_info($this->dealer_id,$this->uid);
        $dealer_info = array();
        if ($dealer_base) {
            //获取经营城市
//            $branch_city = M('branch_city')->where('branch_id = '.$dealer_base['depart_id'])->field('city_code')->find();
//            $city = '';
//            if($branch_city){
                //获取城市名称
                $city = M('apply_city')->where('code = '.$dealer_base['business_city'])->find();
          //  }
            $province_name = $this->get_city_name($dealer_base['province']);

            $city_name = $this->get_city_name($dealer_base['city']);
    
            switch($dealer_base['level']){
                case 0:
                    $dealer_info['content'][0]['type'] = 'avatar';
                    $dealer_info['content'][0]['name'] = '头像';
                    $dealer_info['content'][0]['value'] = $dealer_base['avatar']?$dealer_base['avatar']:get_style_cdnurl().'app/images/bg_head.png';

                    $dealer_info['content'][1]['type'] = 'phone';
                    $dealer_info['content'][1]['name'] = '手机号';
                    $dealer_info['content'][1]['value'] = $dealer_base['pwd_mobile'];

                    $dealer_info['content'][2]['type'] = 'name_value';
                    $dealer_info['content'][2]['name'] = '经营城市';
                    $dealer_info['content'][2]['value'] = empty($city)?'其他':$city['name'];

                    $dealer_info['content'][3]['type'] = 'name_value';
                    $dealer_info['content'][3]['name'] = '账户类型';
                    $dealer_info['content'][3]['value'] = C('DEALER_LEVEL')[$dealer_base['level']];

                    $dealer_info['content'][4]['type'] = 'apply_cert_btn';
                    $dealer_info['content'][4]['name'] = $dealer_base['auth_status']==2?'申请签约':'申请认证';
                    $dealer_info['content'][4]['top_split'] = true;
                    break;
                case 1:
                case 2:
                    if($dealer_base['auth_type']==1) {
                        $dealer_info['content'][0]['type'] = 'username';
                        $dealer_info['content'][0]['name'] = '用户名';
                        $dealer_info['content'][0]['value'] = $dealer_base['user_name'];
                        $dealer_info['content'][0]['editable'] = false;
                        $dealer_info['content'][0]['editable'] = true;


                        $dealer_info['content'][1]['type'] = 'avatar';
                        $dealer_info['content'][1]['name'] = '头像';
                        $dealer_info['content'][1]['value'] = $dealer_base['avatar']?$dealer_base['avatar']:get_style_cdnurl().'app/images/bg_head.png';

                        $dealer_info['content'][2]['type'] = 'name_value';
                        $dealer_info['content'][2]['name'] = '姓名';
                        $dealer_info['content'][2]['value'] = $dealer_base['real_name'];

                        $dealer_info['content'][3]['type'] = 'phone';
                        $dealer_info['content'][3]['name'] = '手机号';
                        $dealer_info['content'][3]['value'] = $dealer_base['pwd_mobile'];

                        $dealer_info['content'][4]['type'] = 'name_value';
                        $dealer_info['content'][4]['name'] = '经营城市';
                        $dealer_info['content'][4]['value'] = empty($city) ? '其他' : $city['name'];
                        $dealer_info['content'][4]['top_split'] = true;

                        $dealer_info['content'][5]['type'] = 'address';
                        $dealer_info['content'][5]['name'] = '通讯地址';
                        $dealer_info['content'][5]['value'] = $province_name['city_name'] . $city_name['city_name'] . $dealer_base['address'];
                        $dealer_info['content'][5]['province'] = empty($province_name['city_name'])?'':$province_name['city_name'];
                        $dealer_info['content'][5]['province_code'] = empty($province_name['city_code'])?'':$province_name['city_code'];
                        $dealer_info['content'][5]['city'] = empty($city_name['city_name'])?'':$city_name['city_name'];
                        $dealer_info['content'][5]['city_code'] = empty($city_name['city_code'])?'':$city_name['city_code'];
                        $dealer_info['content'][5]['address'] = $dealer_base['address'];

                        $dealer_info['content'][6]['type'] = 'name_value';
                        $dealer_info['content'][6]['name'] = '车商类型';
                        $dealer_info['content'][6]['value'] = C('DEALER_TYPE')[$dealer_base['auth_type']];


                        $dealer_info['content'][7]['type'] = 'name_value';
                        $dealer_info['content'][7]['name'] = '车商等级';
                        $dealer_info['content'][7]['value'] = C('DEALER_LEVEL')[$dealer_base['level']];
                    }else{
                        $dealer_info['content'][0]['type'] = 'username';
                        $dealer_info['content'][0]['name'] = '用户名';
                        $dealer_info['content'][0]['value'] = $dealer_base['user_name'];
                        $dealer_info['content'][0]['editable'] = false;

                        $dealer_info['content'][0]['editable'] = true;


                        $dealer_info['content'][1]['type'] = 'avatar';
                        $dealer_info['content'][1]['name'] = '头像';
                        $dealer_info['content'][1]['value'] = $dealer_base['avatar']?$dealer_base['avatar']:get_style_cdnurl().'app/images/bg_head.png';

                        $dealer_info['content'][2]['type'] = 'name_value';
                        $dealer_info['content'][2]['name'] = '公司名称';
                        $dealer_info['content'][2]['value'] = $dealer_base['fullname'];


                        $dealer_info['content'][3]['type'] = 'name_value';
                        $dealer_info['content'][3]['name'] = '授权人姓名';
                        $dealer_info['content'][3]['value'] = $dealer_base['real_name'];

                        $dealer_info['content'][4]['type'] = 'phone';
                        $dealer_info['content'][4]['name'] = '授权人手机号';
                        $dealer_info['content'][4]['value'] = $dealer_base['pwd_mobile'];

                        $dealer_info['content'][5]['type'] = 'name_value';
                        $dealer_info['content'][5]['name'] = '经营城市';
                        $dealer_info['content'][5]['value'] = empty($city)?'其他':$city['name'];
                        $dealer_info['content'][5]['top_split'] = true;

                        $dealer_info['content'][6]['type'] = 'address';
                        $dealer_info['content'][6]['name'] = '通讯地址';
                        $dealer_info['content'][6]['value'] =  $province_name['city_name'].$city_name['city_name'].$dealer_base['address'];
                        $dealer_info['content'][6]['province'] = empty($province_name['city_name'])?'':$province_name['city_name'];
                        $dealer_info['content'][6]['province_code'] = empty($province_name['city_code'])?'':$province_name['city_code'];
                        $dealer_info['content'][6]['city']     = empty($city_name['city_name'])?'':$city_name['city_name'];
                        $dealer_info['content'][6]['city_code']     = empty($city_name['city_code'])?'':$city_name['city_code'];
                        $dealer_info['content'][6]['address']     = $dealer_base['address'];

                        $dealer_info['content'][7]['type'] = 'name_value';
                        $dealer_info['content'][7]['name'] = '车商类型';
                        $dealer_info['content'][7]['value'] = C('DEALER_TYPE')[$dealer_base['auth_type']];

                        $dealer_info['content'][8]['type'] = 'name_value';
                        $dealer_info['content'][8]['name'] = '车商等级';
                        $dealer_info['content'][8]['value'] = C('DEALER_LEVEL')[$dealer_base['level']];
                    }
                    break;

            }
            $this->api_200($dealer_info);
        } else {
            AuctionException::make_throw("500012");
        }
    }


    private function  get_city_name($city_code = 0){
       return  M('addr_area')->where('city_code = '.$city_code)->field("city_name,city_code")->find();
    }

    /**
     * 账户中心 - 基本信息
     * 车商 - 修改基本信息
     * return json 修改基本信息
     */
    public function edit_dealer_base() {
        $avatar = I('data.avatar', '', '', $_FILES);
        if (!empty($avatar)) {
            $rep = array('code' => 200);
            $flag = true;
            if ($avatar['error'] != 0) {
                $flag = false;
                $rep['code'] = 430;
                $rep['msg'] = '照片上传失败';
                trace($rep['msg'] . ',错误码：' . $avatar['error'] . ',time:' . date('Y-m-d H:i:s'),'','ERR',true);
            }
            //图片上传
            if ($flag) {
                $object = 'upload/avatar/' . create_uuid() . '.' . get_extension($avatar['name']);
                $avatar_path = $avatar['tmp_name'];
                try {
                    $aliObject = Image::upload_file_by_file(OSS_BUCKET, $object, $avatar_path);
                    $host = get_content_cdnurl();
                    $rep['data'] = $host . $aliObject;
                   // $this->dealer->updateDealerHead($data);
                } catch (\Exception $e) {
                    $rep['code'] = 430;
                    $rep['msg'] = $e->getMessage();
                }
                $ant = new AntNest();
                $state = $ant->set_user(array('avatar'=>$rep['data'],'account_id'=>$this->uid));
                if($state){
                    $this->api_200('');
                }else{
                    AuctionException::make_throw('100066');
                }
            }
        }

        $city = I('post.area');
        if ($city != '-1') {
            $data['city'] = $city;
            $add = new Address();
            $data['province'] = $add->get_province_code($city);
        }

        $data['address'] = I('post.address');
        $data['postcode'] = I('post.postcode/d');
        $res = $this->dealer->updateDealerInfo($data);
        if ($res === false) {
            AuctionException::make_throw('100065');
        }
        $this->api_200("");
    }


    /**
     * 修改用户信息  针对蚁巢服务
     * @throws AuctionException
     */
    public function edit_user(){
            $avatar = I('data.avatar', '', '', $_FILES);
            if (!empty($avatar)) {
                $rep = array('code' => 200);
                $flag = true;
                if ($avatar['error'] != 0) {
                    $flag = false;
                    $rep['code'] = 430;
                    $rep['msg'] = '照片上传失败';
                    trace($rep['msg'] . ',错误码：' . $avatar['error'] . ',time:' . date('Y-m-d H:i:s'),'','ERR',true);
                }
                //图片上传
                if ($flag) {
                    $object = create_uuid() . '.' . get_extension($avatar['name']);
                    $avatar_path = $avatar['tmp_name'];
                    try {
                        $aliObject = Image::upload_file_by_file(OSS_BUCKET, $object, $avatar_path);
                        $rep['data'] = $aliObject;
                        $data['avatar'] = $rep['data'];
                        //$this->dealer->updateDealerHead($data);
                    } catch (\Exception $e) {
                        $rep['code'] = 430;
                        $rep['msg'] = $e->getMessage();
                    }
                    $ant = new AntNest();
                    $state = $ant->set_user(array('account_avatar'=>$rep['data'],'account_id'=>$this->uid));
                    if($state){
                        $this->api_200('');
                    }else{
                        AuctionException::make_throw('100066');
                    }
                }
                $this->api_200('');
            }else{
                $user_name = I('post.username');
                if(empty($user_name)){
                    AuctionException::make_throw('100066');
                }
                $ant = new AntNest();
                $option = array(
                    'account_id'=>$this->uid,
                    'account_name'=>$user_name,
                );
                $result = $ant->set_user($option);
                if($result){
                    $this->api_200('');
                }
                AuctionException::make_throw('100066');
            }
    }

    /**
     * 修改手机号
     * @throws AuctionException
     */
    public function edit_user_mobile(){
        $mobile = I('post.mobile');
        $v_code = I('post.v_code');
        $type   = I('post.type');
        $number = I('post.number');
        $ant = new AntNest();
        $option['ver_code'] = $v_code;
        $option['number']   =  $number;
        $option['mobile']   = $mobile;
        $redis = new PhpRedis();

        $arr = [
            'uid'=>$this->uid
        ];
        $keyName = getRedisKeyByCode('REDIS_KEY','100004',$arr);

        if($type==1){
            $vCode = $ant->sms_verify($option);
            if($vCode){
                //设置步骤 先验证原有手机
                $redis->set($keyName,"1");
                $this->api_200('');
            }
            AuctionException::make_throw('200086');
        }elseif($type == 2){
            //获取步骤 查询是否已验证手机
            $step  = $redis->get($keyName);
            if($step!='1'){
                AuctionException::make_throw('200093');
            }
            $vCode = $ant->sms_verify($option);
            if($vCode){
                $state = $ant->set_user(array('account_id'=>$this->uid,'mobile'=>$mobile));
                //清除步骤信息
                $redis->del($keyName);
                if($state){
                    $this->api_200('');
                }
                AuctionException::make_throw('100066');
            }
            AuctionException::make_throw('200086');
        }
        AuctionException::make_throw('1200002');
    }



    /**
     * 修改通讯地址
     * @throws AuctionException
     */
    public function edit_address(){
        $data['address'] = I('post.address');
        $data['province'] = I('post.province/d');
        $data['city']     = I('post.city/d');
        if(empty($data['province'])){
            echo json_encode(array('code'=>401,'msg'=>'请选择省份'));
            exit;
        }
        if(empty($data['city']) && !in_array($data['province'], array(2,24,25,31))){//非直辖市 检查城市
            echo json_encode(array('code'=>402,'msg'=>'请选择城市'));
            exit;
        }

        $res = $this->dealer->updateDealerInfo($data);
        if ($res === false) {
            AuctionException::make_throw('100065');
        }
        $this->api_200("");
    }


    /**
     * 账户中心 - 修改密码
     * 车商 - 修改密码
     * $param pwd,new_pwd,new_pwd_confirm md5过的密码
     * return json 修改是否成功
     */
    public function update_pwd() {
        $pwd = I("post.password", '');
        $new_pwd = I("post.new_password", '');
        $new_pwd_confirm = I("post.new_password_confirm", '');
        $uid = I('post.uid');
        $dealer_id = I('post.dealer_id');
        $version = I('post.version');
        
        //校验传输密码是否正确
        if(version_compare($version,'1.5.1','>')){
            $pwd = AuthController::dico_rsa($pwd);
            $new_pwd = AuthController::dico_rsa($new_pwd);
            $new_pwd_confirm = AuthController::dico_rsa($new_pwd_confirm);
        }
        $is_md5 = is_md5(array($pwd,$new_pwd,$new_pwd_confirm));
        if( !$is_md5 ) exit(json_encode(array('code'=>500,'msg'=>'系统错误')));
        if (empty($pwd)) {
            AuctionException::make_throw('200030');
        }
        if (empty($new_pwd)) {
            AuctionException::make_throw('200031');
        }
        if($new_pwd != $new_pwd_confirm){
            AuctionException::make_throw('200029');
        }

        if ($new_pwd == md5('123456')) {
            AuctionException::make_throw('200040');
        }

        if (empty($new_pwd_confirm)) {
            AuctionException::make_throw('200032');
        }
        if ($new_pwd !== $new_pwd_confirm) {
            AuctionException::make_throw('300010');
        }
        //验证密码
        $dealer = new dealer($dealer_id);
        $ok = $dealer->change_password(array('pwd_old'=>$pwd,'account_id'=>$uid,'pwd_new'=>$new_pwd));
        if ($ok['code']==='000000') {
            $this->api_200("");
        }
        AuctionException::make_throw($ok['code'],$ok['msg']);

    }
    /**
     * 账户中心 - 强制修改密码
     * 车商 - 修改密码
     * $param pwd,new_pwd,new_pwd_confirm md5过的密码
     * return json 修改是否成功
     */
    public function update_pwd_force() {
        $new_pwd = I("post.new_password", '');
        $new_pwd_confirm = I("post.new_password_confirm", '');
        $auth_code = I("post.sms_code", '');
        $type = 1;//
        if (empty($new_pwd)) {
            AuctionException::make_throw('200031');
        }
        if ($new_pwd == md5('123456')) {
            AuctionException::make_throw('200040');
        }

//        $check_new_pwd_len = preg_match('/^[\w\W]{6,16}$/', $new_pwd);
//        if(!$check_new_pwd_len){
//             AuctionException::make_throw('200036');
//        }
        if (empty($new_pwd_confirm)) {
            AuctionException::make_throw('200032');
        }
        if ($new_pwd !== $new_pwd_confirm) {
            AuctionException::make_throw('300010');
        }
        if (empty($auth_code)) {
            AuctionException::make_throw('200085');
        }

        $user_dealer_info = $this->dealer->dealer_base_info($this->dealer_id,$this->uid);

        //蚁巢服务
        //验证手机短信验证码
        $ant = new AntNest();
        $option = array();
        $option['ver_code'] = $auth_code;
        $option['number'] =  12;
        $option['mobile'] = $user_dealer_info['pwd_mobile'];
        $vCode = $ant->sms_verify($option);
        if(!$vCode){
            AuctionException::make_throw('200086');
        }

        //修改密码
        $data = array();
        $data['account_type'] = 2;
        $data['pwd_new'] = $new_pwd;
        $data['number'] = 12;
        $data['mobile'] = $user_dealer_info['pwd_mobile'];
        $info = $ant->retrieve_pwd($data);
        if($info['code']=='000000'){
            $this->api_200("");
        }else{
            AuctionException::make_throw($info['code'],$info['msg']);
        }
    }
    //发送修改密码的验证码
    public function send_mob_code(){

        //蚁巢服务
        $ant = new AntNest();
        $user_info = $ant->get_userinfo($this->uid);
        $phone =  $user_info['pwd_mobile'];
        //$type = 1;

        if (empty($phone)) {
            AuctionException::make_throw('200007');
        }
        if (!validatePhone($phone)) {
            AuctionException::make_throw('200071');
        }

        $option  = array();
        $option['mobile'] = $phone;
        $option['number'] = 12;
        $state = $ant->get_sms($option);
        if($state['code']==='000000'){
            $this->api_200("'验证码已发送，请注意查收'");
        }
        AuctionException::make_throw($state['code'],$state['msg']);
    }

    /**
     * 账户中心 - 提车人管理
     * 车商 - 提车人列表
     * return json 提车人列表
     */
    public function get_take_man_list() {
        $page = I('post.page/d', 1);
        $page_size = I('post.page_size/d', 20);
        $params = array(
            'dealer_id' => $this->dealer_id
        );
        $take_man_list = TakeMan::getList($page, $page_size, $params);
        if (array_filter($take_man_list)) {
            $this->api_200($take_man_list);
        } else {
            AuctionException::make_throw('500007');
        }
    }

    /**
     * 账户中心 - 提车人管理
     * 车商 - 提车人信息
     * return json 提车人信息
     */
    public function get_take_man() {
        $man_id = I("param.man_id/d");
        $take_man[] = $this->take_man->detail($man_id);
        if (array_filter($take_man)) {
            $take_man_info = array();
            foreach ($take_man as $tm) {
                $take_man_info['real_name'] = $tm['real_name'];
                $take_man_info['sex'] = $tm['sex'];
                $take_man_info['mobile'] = $tm['mobile'];
                $take_man_info['idcard'] = $tm['idcard'];
                $take_man_info['take_num'] = $tm['take_num'];
                $take_man_info['status'] = $tm['status'];
                $take_man_info['is_contact_person'] = $tm['is_contact_person'];
            }
            $this->api_200($take_man_info);
        } else {
            AuctionException::make_throw('500007');
        }
    }

    /**
     * 账户中心 - 提车人管理
     * 车商 - 新增提车人
     * return json 新增提车人
     */
    public function add_take_man() {
        $data = array();
        $data['real_name'] = I('post.real_name');
        if (empty($data['real_name'])) {
            AuctionException::make_throw('500005');
        }
        $data['sex'] = I('post.sex/d');
        $data['mobile'] = I('post.mobile/d');
        if (empty($data['mobile'])) {
            AuctionException::make_throw('200007');
        }
        $data['idcard'] = I('post.idcard');
        if (!validateIdCard($data['idcard'])) {
            AuctionException::make_throw('500064');
        }
        //未签约不可添加提车人
        $dealer = new Dealer($this->dealer_id);
        $dealer_info = $dealer->detail();
        if($dealer_info['is_agree_agreement']==0){
            AuctionException::make_throw('260024');
        }

        $data['take_num'] = 0;
        $res = $this->take_man->add($data);
        if ($res === false) {
            AuctionException::make_throw("100066");
        }
        $this->api_200("");
    }

    /**
     * 车商 - 修改提车人
     */
    public function edit_take_man() {
        $man_id = I('post.man_id/d');
        if (empty($man_id)) {
            AuctionException::make_throw('500006');
        }
        $data['man_id'] = $man_id;
        $data['real_name'] = I('post.real_name');
        $data['sex'] = I('post.sex/d');
        $data['mobile'] = I('post.mobile/d');
        if (empty($data['mobile'])) {
            AuctionException::make_throw('200007');
        }
        $data['idcard'] = I('post.idcard');
        if (!validateIdCard($data['idcard'])) {
            AuctionException::make_throw('500064');
        }
        $data['status'] = I('post.status/d');
        $res = $this->take_man->edit($data);
        if ($res === false) {
            AuctionException::make_throw("100065");
        }
        $this->api_200("");
    }

    /**
     * 车商 - 删除提车人
     */
    public function del_take_man() {
        try {
            $man_id = I('post.man_id/d');
            if (!$man_id) {
                AuctionException::make_throw("500006");
            }
            $res = $this->take_man->del($man_id);
            if ($res) {
                $this->api_200("");
            } else {
                AuctionException::make_throw("100065");
            }
        } catch (AuctionException $e) {
            AuctionException::make_throw("100065");
//            echo json_encode(array('code' => $e->getCode(), msg => $e->getMessage()));
        }
    }

    /**
     * 客户中心
     * 车商 - 我的客户经理详情
     * return json 我的客户经理详情
     */
    public function get_dealer_manager() {
        $dealer_manager[] = $this->dealer->my_manager();
        if (array_filter($dealer_manager)) {
            $dealer_manager_info = array();
            foreach ($dealer_manager as $dm) {
                $dealer_manager_info['avatar'] = $dm['avatar']?$dm['avatar']:get_style_cdnurl().'app/images/bg_head.png';
                $dealer_manager_info['real_name'] = $dm['real_name'];
                $dealer_manager_info['mobile'] = $dm['mobile'];
            }
            $this->api_200($dealer_manager_info);
        } else {
            AuctionException::make_throw('500013');
        }
    }

    /**---------------------------2016双12 砍价活动-------------------------
     *
     判断是否超预算
     判断今天是否已生成过（查邀请记录表）
     记入邀请表au_dealer_invite_log，活动ID，车商ID，时间，签名等 。
     生成新的分享链接（根据算法生成新的sign)，同来拍车APP分享链接。
     */
    public function invite(){

        if (empty($this->dealer_id)) {
           AuctionException::make_throw('360011');
        }

        $dealer_id = $this->dealer_id;
        $activity_id = I('request.aid',1);

        $redis = new PhpRedis();
        $short_param = short_url($dealer_id);
        $arr = [
            'shorturl'=>$short_param
        ];
        $keyName = getRedisKeyByCode('REDIS_KEY','100005',$arr);
        $is_short_param = $redis->get($keyName);
        if(!$is_short_param){
            $redis->set($keyName,$dealer_id);
        }

        $dealer = new Dealer($dealer_id);
        //车商信息
        $dealer_info = $dealer->dealer_base_info($dealer_id,$this->uid);

        //活动是否有效
        $this->check_activity_valid($dealer,$activity_id);


        //签名
        $sign = sha1($activity_id.$dealer_info['user_name'].$dealer_info['pwd_password'].date('Ydm').'lpaiche.com');

        //判断今天是否已邀请过
        $invite_info= $dealer->get_invite_log($activity_id,date('Y-m-d'));
        if(empty($invite_info)){
            //记录邀请码
            $data = array();
            $data['dealer_id'] = $this->dealer_id;
            $data['activity_id'] = $activity_id;
            $data['sign'] = $sign;
            $dealer->add_invite_log($data);
        }

        //准备今天的奖池
        $arr = [
            'date'=>date('Ymd')
        ];
        $r_key = getRedisKeyByCode('REDIS_KEY','100006',$arr);
        if(!$redis->exists($r_key)){
            //获取昨日未用完奖品
            $arr = [
                'date'=>date('Ymd',strtotime('-1 day'))
            ];
            $yr_key = getRedisKeyByCode('REDIS_KEY','100007',$arr);

            $yscore_10 =  0;
            $yscore_20 =  0;
            $yscore_30 =  0;
            $yscore_50 =  0;
            $yscore_100 = 0;
            $yscore_200 = 0;
            if($redis->exists($yr_key)){
                $yscore_10 = $redis->zscore($yr_key,10);
                $yscore_20 = $redis->zscore($yr_key,20);
                $yscore_30 = $redis->zscore($yr_key,30);
                $yscore_50 = $redis->zscore($yr_key,50);
                $yscore_100 = $redis->zscore($yr_key,100);
                $yscore_200 = $redis->zscore($yr_key,200);
            }
            //
            $redis->zadd($r_key,$yscore_10+20000,10);
            $redis->zadd($r_key,$yscore_20+6500,20);
            $redis->zadd($r_key,$yscore_30+2500,30);
            $redis->zadd($r_key,$yscore_50+500,50);
            $redis->zadd($r_key,$yscore_100+300,100);
            $redis->zadd($r_key,$yscore_200+200,200);
        }


        //判断库存
        $a_info=$dealer->activity_info($activity_id);
        if($a_info['amount']<=$a_info['amount_used']){
            AuctionException::make_throw('360004');
        }

        //分享
        $share = array();
        $share_url =  "http://appapi.lpaiche.com" . U("Dealer/cutdown", ['aid'=>$activity_id,'param'=>$short_param,'invite_code'=>$sign]);
        //echo $share_url;
        $share['title'] = '【来拍车】双12，乐翻天，天天都有大奖拿';
        $share['desc'] = "您的朋友".showHideMobile($dealer_info['contact_mobile'])."邀请您帮他砍价";
        $share['image'] = "http://appapi.lpaiche.com/images/clcw.png";
        $share['url'] = $share_url;
        $this->assign('share',$share);

        $this->display();
   }

    //帮砍H5页面
    public function cutdown(){

        //判断是否满砍价条件
        $ret = $this->pub_get();
        $dealer_id = $ret['dealer_id'];
        $activity_id = $ret['activity_id'];
        $sign = $ret['sign'];
        $this->pub_verify($dealer_id,$activity_id,$sign);

        $this->display();
    }

    /**
     * 砍价(给车商发放代金券)
     * @return json
     */
    public function do_cutdown(){

        //判断前置条件
        $ret = $this->pub_get();
        $dealer_id = $ret['dealer_id'];
        $activity_id = $ret['activity_id'];
        $sign = $ret['sign'];
        $mobile = $ret['mobile'];
        $code = $ret['code'];
        $this->pub_verify($dealer_id,$activity_id,$sign,$mobile,$code);

        //车商对象
        $dealer = new Dealer($dealer_id);

        //抽奖
        $money = $dealer->prize_draw();

        //活动信息
        $activity_info = $dealer->activity_info($activity_id);

        //开启事务
        M()->startTrans();
        //生成并发送代金券给车商
        $res1 = $dealer->send_dealer_coupon($activity_info['name'],$money);

        //更新库存amount_used
        $res2 = $dealer->update_activity($activity_id,array('amount_used'=>$activity_info['amount_used']+$money));

        //更新库存代金券数量
        $activity_coupon_info = $dealer->activity_coupon_info($activity_id,$money);
        $data = array();
        $data['used_num'] = $activity_coupon_info['used_num']+1;
        $res3 = $dealer->update_activity_coupon($activity_id,$money,$data);

        //邀请信息
        $invite_info = $dealer->get_invite_info($activity_id,$sign);

        //记录砍价日志信息
        $data = array();
        $data['invite_id'] = $invite_info['dil_id'];
        $data['mobile'] = $mobile;
        $data['money'] = $money;
        $data['ip'] = get_real_ip();
        $res4 = $dealer->add_cutdown_log($data);

        if($res1 && $res2 !==false && $res3 !==false && $res4){
            //事务提交
            M()->commit();
        }else{
            //事务回滚
            M()->rollback();
            AuctionException::make_throw('360009');
        }

        //输出结果
        $this->api_200($data);
    }



    /**
     *发送验证码
     */
    public function send_verify_code(){
        //业务参数
        $phone  = I('request.phone');
        if (empty($phone)) {
            AuctionException::make_throw('200007');
        }
        if (!validatePhone($phone)) {
            AuctionException::make_throw('200071');
        }
        //判断前提条件
        $ret = $this->pub_get();
        $dealer_id = $ret['dealer_id'];
        $activity_id = $ret['activity_id'];
        $sign = $ret['sign'];
        $this->pub_verify($dealer_id,$activity_id,$sign,$phone);

        //调用蚁巢发送短信
        $ant = new AntNest();
        $option  = array();
        $option['mobile'] = $phone;
        $option['number'] = 12;
        $state = $ant->get_sms($option);
        if($state['code']=='000000'){
            $this->api_200(array());
        }else{
            trace('蚁巢错误码：'.var_export($state,true));
            AuctionException::make_throw('200082');
        }
    }

    private function pub_get(){
        $activity_id  = I('request.aid');
        $short_param  = I('request.param');
        $sign  = I('request.invite_code');
        if(empty($activity_id) || empty($short_param) || empty($sign)){
            AuctionException::make_throw('800050');
        }
        //
        $mobile = I('request.phone');
        $code = I('request.code');

        //验证
        $redis = new PhpRedis();
        $arr = [
            'shorturl'=>$short_param
        ];
        $keyName = getRedisKeyByCode('REDIS_KEY','100005',$arr);
        $dealer_id = $redis->get($keyName);
        if(!$dealer_id){
            AuctionException::make_throw('500001');
        }
        //
        $arr = array();
        $arr['activity_id'] = $activity_id;
        $arr['dealer_id'] = $dealer_id;
        $arr['sign'] = $sign;
        $arr['mobile'] = $mobile;
        $arr['code'] = $code;
        return $arr;
    }
    /**
     * 通用验证
     * @param $dealer_id
     * @param $activity_id
     * @param $sign
     * @param $mobile
     */
    private  function pub_verify($dealer_id,$activity_id,$sign,$mobile='',$code=''){

        //
        $dealer = new Dealer($dealer_id);

        //验证短信验证码
        if($code){

            $ant = new AntNest();
            $option  = array();
            $option['mobile'] = $mobile;
            $option['number'] = 12;
            $option['ver_code'] = $code;
            $state = $ant->sms_verify($option,$error_msg);
            if(!$state){
                AuctionException::make_throw($error_msg['code'],$error_msg['msg']);
            }
        }

        //活动是否有效
        $this->check_activity_valid($dealer_id,$activity_id);

        //邀请码已失效，请您的朋友重新分享
        $invite_info = $dealer->get_invite_info($activity_id,$sign);
        if(!$invite_info){
            AuctionException::make_throw('360006');
        }

        //获取上限配置
        $sysConf = new SystemConf();
        $conf = $sysConf->getConfByName('DEALER_INVITE_UPPER_LIMIT');
        $upper_limit = $conf['value']>0?$conf['value']:20;
        //邀请码砍价人数已达上限，明天再来吧！
        $cnt = $dealer->get_upper_limit($invite_info['dil_id']);
        if($cnt>=$upper_limit){
            AuctionException::make_throw('360007');
        }
        if($mobile){
            //是否已砍过
            $res = $dealer->get_cutdown_info($invite_info['dil_id'],$mobile);
            if($res){
                AuctionException::make_throw('360008');
            }
        }

        //今日奖池判断
        $redis = new PhpRedis();
        $arr = [
            'date'=>date('Ymd')
        ];
        $keyName = getRedisKeyByCode('REDIS_KEY','100006',$arr);

        $a = $redis->zrange($keyName,0,-1,true);
        if(array_sum($a)<=0){
            trace('今日奖池奖品已全部发送完毕','','INFO',true);
            AuctionException::make_throw('360004');
        };

        //库存判断
        $a_info=$dealer->activity_info($activity_id);
        if($a_info['amount']<=$a_info['amount_used']){
            trace('库存全部奖品均已发放完毕','','INFO',true);
            AuctionException::make_throw('360004');
        }
    }

    /**
     * 活动是否有效
     */
    private  function check_activity_valid($dealer_id,$activity_id){
        $dealer = new Dealer($dealer_id);
        $info = $dealer->activity_info($activity_id);
        if(empty($info)){
            AuctionException::make_throw('360001');
        }
        //判断活动是否已过期
        if(date('Ymd')<date('Ymd',strtotime($info['starttime']))){
            AuctionException::make_throw('360002');
        }elseif(date('Ymd')>date('Ymd',strtotime($info['endtime']))){
            AuctionException::make_throw('360003');
        }

    }

    /**
     *
     * 获取车商等级是否可以智能报价
     * return json
     */
    public function get_dealer_identity(){
        $order_id = I('post.order_id/d');
        $dealer_id = I('post.dealer_id/d');
        $dealer = new Dealer($dealer_id);
        $dealer_info = $dealer->detail();
        if($dealer_info['level'] != 0){
            $o = new AuOrder($order_id);
            $order_info = $o->detail();
            $car = new Car($order_info['car_id']);
            $car_info = $car->detail();
            $data['top_price'] = intval($car_info['reserve_price'] * 1.2);
            $info = $dealer->get_final_price($order_id,$dealer_id);
            if($info[0]['limit_price']){
                $data['last_set_price'] = intval($info[0]['limit_price']);
            }else{
                $data['last_set_price'] = 0;
            }
            $data['desc'] = "1、自动出价 \n2、每次加价300元 \n3、达到智能加价金额上限后自动停止 \n4、建议预留充足保证金 \n5、存在无法加价到全额上限的可能性 ";
            $this->api_200($data);
        }else{
            echo json_encode(array('code'=>'302','msg'=>'抱歉，初级买家无法设置智能出价，请先认证签约！'));
        }
    }
    /**
     *
     * 获取车商智能出价列表
     * return json
     */
    public function auto_bidding_history(){
        $page = I('post.page','1');
        $page_size = I('post.page_size','20');
        $params = array();
        $order_no = I('post.order_no');
        if($order_no){
            $is_valid_order_no = AuOrder::is_valid_order_no($order_no);
            if($is_valid_order_no){
                $o = new AuOrder($order_no);
                $order_info = $o->detail();
                $params['order_id'] = $order_info['order_id'];
            }else{
                trace('拍单号无效：'.$order_no,'','DEBUG',true);
                $data = array(
                    'currentpage' => $page,
                    'pagesize' => $page_size,
                    'maxcount' => 0,
                    'maxpage' => 0,
                    'list' => array()
                );
                $this->api_200($data);
            }
        }
        $params['type'] = I('post.type');
        $params['start_time'] = I('post.start_time');
        $params['end_time'] = I('post.end_time');
//        if($params['start_time'] && $params['end_time']){
//            if(strtotime($params['start_time']) > strtotime($params['end_time'])){
//                AuctionException::make_throw('700046');
//            }
//        }else if($params['start_time']){
//            if(strtotime($params['start_time']) > time()){
//                AuctionException::make_throw('700046');
//            }
//        }
        $dealer = new Dealer($this->dealer_id);
        $result = $dealer->get_auto_list($params,$page,$page_size);
        $list = $result['list'];
        $total = $result['total'];
        $auto_price = array();
        foreach($list as $k => $v){
            $o = new AuOrder($v['order_id']);
            $orderInfo = $o->detail();
            $auto_price[$k]['order_no'] = "拍单编号: ".$orderInfo['order_no'];
            $auto_price[$k]['top_price'] = intval($v['limit_price'])."元";
            $auto_price[$k]['state_name'] = $v['status'] == 0 ? '停止' : '设置';
            $auto_price[$k]['state'] = $v['status'];
            $auto_price[$k]['create_time'] = $v['createtime'] == '0000-00-00 00:00:00' ? $v['modifytime'] : $v['createtime'] ;
        }
        $data = array(
            'currentpage' => $page,
            'pagesize' => $page_size,
            'maxcount' => $total,
            'maxpage' => ceil($total / $page_size),
            'list' => $auto_price
        );
        $this->api_200($data);
    }

    public function set_auto_bid($type=1){
        $dealer_id = $this->dealer_id;
        $order_id = $this->order_id;
        if(empty($dealer_id)){
            AuctionException::make_throw('500001');
        }
        if(empty($order_id)){
            AuctionException::make_throw('700027');
        }

        $type = I('post.type',$type);
        if($type==1){
            $limit_price = I('post.top_price');
            if(empty($limit_price)){
                AuctionException::make_throw('360013');
            }
        }
        //weaver 端处理并返回结果
        try {
            $handle = new THttpClient(C('WEAVER_URL'), 80, '/Auction/run');
            $transport = new TBufferedTransport($handle);
            $protocol = new TBinaryProtocol($transport);
            $auctionProtocol = new TMultiplexedProtocol($protocol, 'AuctionService');
            $auctionService = new AuctionServiceClient($auctionProtocol);
            if($type==1){
                $res = $auctionService->intelBidSet($dealer_id,$order_id, $limit_price);
            }else{
                $res = $auctionService->intelBidStop($dealer_id,$order_id);
            }
            if(!$res){
                AuctionException::make_throw('360016');
            }
        } catch (TException $tx) {
            $code = $tx->getCode();
            $msg = $tx->getMessage();
            AuctionException::make_throw($code,$msg);
        }

        $this->api_200(array());
    }

    public function stop_auto_bid(){
        $this->set_auto_bid(0);
    }


}
